package org.jeecg.modules.extbpm.process.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.bpm.service.ActivitiService;
import org.jeecg.modules.bpm.service.impl.ActProcessService;
import org.jeecg.modules.extbpm.process.common.WorkFlowGlobals;
import org.jeecg.modules.extbpm.process.entity.*;
import org.jeecg.modules.extbpm.process.exception.BpmException;
import org.jeecg.modules.extbpm.process.pojo.ProcessDeploymentInfo;
import org.jeecg.modules.extbpm.process.pojo.RoleInfo;
import org.jeecg.modules.extbpm.process.pojo.UserInfo;
import org.jeecg.modules.extbpm.process.service.*;
import org.jeecg.modules.extbpm.util.JSONHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.concurrent.FutureTask;

/**
 * @Title: Controller
 * @Description: 流程表
 * @author： jeecg-boot
 * @date：   2019-03-15
 * @version： V1.0
 */
@RestController("extActProcessController")
@RequestMapping("/act/process/extActProcess")
@Slf4j
public class ExtActProcessController {
	@Autowired
	private IExtActProcessService extActProcessService;
	@Autowired
	private ActivitiService activitiService;
	@Autowired
	private IExtActProcessNodeService extActProcessNodeService;
	@Autowired
	private IExtActProcessFormService extActProcessFormService;
	@Autowired
	private ActProcessService actProcessService;
	@Autowired
	private IExtActProcessNodeDeploymentService extActProcessNodeDeploymentService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	/**
	  * 分页列表查询
	 * @param extActProcess
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<ExtActProcess>> queryPageList(ExtActProcess extActProcess,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<ExtActProcess>> result = new Result<IPage<ExtActProcess>>();
		QueryWrapper<ExtActProcess> queryWrapper = QueryGenerator.initQueryWrapper(extActProcess, req.getParameterMap());
		Page<ExtActProcess> page = new Page<ExtActProcess>(pageNo, pageSize);
		IPage<ExtActProcess> pageList = extActProcessService.page(page, queryWrapper);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param extActProcess
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<ExtActProcess> add(@RequestBody ExtActProcess extActProcess) {
		Result<ExtActProcess> result = new Result<ExtActProcess>();
		try {
			extActProcessService.save(extActProcess);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param extActProcess
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<ExtActProcess> edit(@RequestBody ExtActProcess extActProcess) {
		Result<ExtActProcess> result = new Result<ExtActProcess>();
		ExtActProcess extActProcessEntity = extActProcessService.getById(extActProcess.getId());
		if(extActProcessEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = extActProcessService.updateById(extActProcess);
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<ExtActProcess> delete(@RequestParam(name="id",required=true) String id) {
		Result<ExtActProcess> result = new Result<ExtActProcess>();
		ExtActProcess extActProcess = extActProcessService.getById(id);
		if(extActProcess==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = extActProcessService.removeById(id);
			if(ok) {
				//删除节点
				LambdaQueryWrapper<ExtActProcessNode> queryWrapperNode = new LambdaQueryWrapper<ExtActProcessNode>();
				queryWrapperNode.eq(ExtActProcessNode::getProcessId, id);
				extActProcessNodeService.remove(queryWrapperNode);
				//删除业务配置
				LambdaQueryWrapper<ExtActProcessForm> queryWrapperForm= new LambdaQueryWrapper<ExtActProcessForm>();
				queryWrapperForm.eq(ExtActProcessForm::getProcessId, id);
				extActProcessFormService.remove(queryWrapperForm);
				result.success("删除成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<ExtActProcess> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<ExtActProcess> result = new Result<ExtActProcess>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.extActProcessService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<ExtActProcess> queryById(@RequestParam(name="id",required=true) String id) {
		Result<ExtActProcess> result = new Result<ExtActProcess>();
		ExtActProcess extActProcess = extActProcessService.getById(id);
		if(extActProcess==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(extActProcess);
			result.setSuccess(true);
		}
		return result;
	}
	
	/**
	  *  流程发布
	 * @param extActProcess
	 * @return
	 */
	@PutMapping(value = "/deployProcess")
	public Result<ExtActProcess> deployProcess(@RequestBody HashMap<String, String> map) {
		String id=map.get("id");
		Result<ExtActProcess> result = new Result<ExtActProcess>();
		ExtActProcess extActProcessEntity = extActProcessService.getById(id);
		if(extActProcessEntity==null) {
			result.error500("未找到对应实体");
		}else {
			try {
				extActProcessService.deployProcess(extActProcessEntity);
			result.success("发布成功");
			} catch (Exception e) {
				e.printStackTrace();
				result.success("发布失败");
			}
		}
		return result;
	}
	
	
	/**
	  * 分页流程版本查询
	 * @return
	 */
	@GetMapping(value = "/processDeploymentList")
	public Result<IPage<ProcessDeploymentInfo>> processDeploymentList(@RequestParam("processKey") String processKey,
									  HttpServletRequest req) {
		Result<IPage<ProcessDeploymentInfo>> result = new Result<IPage<ProcessDeploymentInfo>>();
		List<ProcessDefinition> processDefinitionList = new ArrayList<ProcessDefinition>();
		//根据流程id获取该流程发布的流程
		processDefinitionList = activitiService.processDefinitionListByProcesskey(processKey);
//		List<Object[]> objects = new ArrayList<Object[]>();
//		for (ProcessDefinition processDefinition : processDefinitionList) {
//			String deploymentId = processDefinition.getDeploymentId();
//			Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
//			objects.add(new Object[] { processDefinition, deployment });
//		}
		List<ProcessDeploymentInfo> processDeploymentInfoList = new ArrayList<ProcessDeploymentInfo>();
		for (ProcessDefinition processDefinition : processDefinitionList) {
			ProcessDeploymentInfo info = new ProcessDeploymentInfo();
			info.setId(processDefinition.getId());
			info.setDeploymentId(processDefinition.getDeploymentId());
			info.setDiagramResourceName(processDefinition.getDiagramResourceName());
			info.setKey(processDefinition.getKey());
			info.setName(processDefinition.getName());
			info.setResourceName(processDefinition.getResourceName());
			String suspensionState = "1";
			if(processDefinition.isSuspended()) {
				suspensionState = "0";
			}
			info.setSuspensionState(suspensionState);
			info.setVersion(processDefinition.getVersion());
			processDeploymentInfoList.add(info);
		}
		
		IPage<ProcessDeploymentInfo> list = new Page<ProcessDeploymentInfo>();
		list.setRecords(processDeploymentInfoList);
		result.setSuccess(true);
		result.setResult(list);
		return result;
	}
	
	/**
	 * 删除
	 * @param deploymentIds
	 * @return
	 */
	@DeleteMapping(value = "/deleteDeployment")
	public Result deleteDeployment(@RequestParam(name = "ids", required = true) String ids,@RequestParam(name = "processKey", required = true) String processKey) {
		if(oConvertUtils.isNotEmpty(ids)) {
			for (String id : Arrays.asList(ids.split(","))) {
				actProcessService.deleteDeployment(id);
				//删除发布节点
				LambdaQueryWrapper<ExtActProcessNodeDeployment> queryWrapperNodeDeployment = new LambdaQueryWrapper<ExtActProcessNodeDeployment>();
				queryWrapperNodeDeployment.eq(ExtActProcessNodeDeployment::getDeploymentId, id);
				extActProcessNodeDeploymentService.remove(queryWrapperNodeDeployment);
				List<ProcessDefinition> processDefinitionList = activitiService.processDefinitionListByProcesskey(processKey);
				if(processDefinitionList==null||processDefinitionList.size()<=0) {
					// 更新发布的状态
					LambdaQueryWrapper<ExtActProcess> queryWrapper = new LambdaQueryWrapper<ExtActProcess>();
					queryWrapper.eq(ExtActProcess::getProcessKey, processKey);
					ExtActProcess extActProcessEntity = extActProcessService.getOne(queryWrapper);
					extActProcessEntity.setProcessStatus(WorkFlowGlobals.Process_Deploy_NO);
					extActProcessService.updateById(extActProcessEntity);
				}
			}
		}
		return new Result();
	}
	
	/**
	  *  同步流程用户
	 * @param extActProcess
	 * @return
	 */
	@PutMapping(value = "/doSyncUser")
	public Result<ExtActProcess> doSyncUser(HttpServletRequest request) {
		Result<ExtActProcess> result = new Result<ExtActProcess>();
		try {
			String syncUserFlag = SyncUserThreadTask.syncUserFlag;
			if(syncUserFlag!=null&&"1".equals(syncUserFlag)){
				result.success("正在同步中");
			}else{
				SyncUserThreadTask.syncUserFlag = "1";
				String username = JwtUtil.getUserNameByToken(request);
				//new Thread(new SyncUserThreadTask(username)).start();
				FutureTask<Boolean> futureTask = new FutureTask<Boolean>(new SyncUserThreadTask(username));
				Thread newThread = new Thread(futureTask);
				newThread.start();
				try {
					Boolean threadResult = futureTask.get();
				} catch (Exception e) {
					e.printStackTrace();
					log.error("fail:", e);
				}
				//result.success("同步操作已开始");
				result.success("同步完成");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.error500("同步异常");
		}
		return result;
	}
	/**
	  *  同步流程用户
	 * @param extActProcess
	 * @return
	 */
	@PutMapping(value = "/doSyncUserByUserName")
	public Result<ExtActProcess> doSyncUserByUserName(@RequestBody HashMap<String, String> map) {
		String userName=map.get("userName");
		Result<ExtActProcess> result = new Result<ExtActProcess>();
		try {
			LoginUser user = sysBaseAPI.getUserByName(userName);
			if(CommonConstant.ACT_SYNC_1.equals(user.getActivitiSync())) {
				//同步则进行同步用户和角色信息
				UserInfo userInfo = new UserInfo();
				userInfo.setUuid(user.getId());
				userInfo.setFirstName(user.getRealname());
				userInfo.setEmail(user.getEmail());
				userInfo.setId(user.getUsername());
				List<RoleInfo> roleList = extActProcessService.getSysRolesByUserId(userInfo.getUuid());
				extActProcessService.saveActIdMembership(userInfo, roleList);
			}else {
				//不同步删除用户信息
				extActProcessService.deleteActIdMembership(userName);
			}
			result.success("同步完成");
		} catch (Exception e) {
			e.printStackTrace();
			result.error500("同步异常");
		}
		return result;
	}

	/**
	 * 流程提交接口（online，自定义开发）
	 * @param map
	 * @param request
	 * @return
	 */
	@PostMapping(value = "startMutilProcess")
	public Result<Object> startMutilProcess(@RequestBody HashMap<String, String> map,
											HttpServletRequest request) {
		String flowCode = map.get("flowCode");
		String id = map.get("id");
		String formUrl = map.get("formUrl");
		String formUrlMobile = map.get("formUrlMobile");
		Result<Object> result = new Result<Object>();
        result.setMessage("流程发起成功！");
		try {
			if(oConvertUtils.isEmpty(flowCode)) {
				throw new BpmException("flowCode参数不能为空");
			}
			if(oConvertUtils.isEmpty(id)) {
				throw new BpmException("id参数不能为空");
			}
			if(oConvertUtils.isEmpty(formUrl)) {
				throw new BpmException("formUrl参数不能为空");
			}
			ExtActProcessForm extActProcessForm = null;
			Map<String, Object> dataForm = new HashMap<String, Object>();
			//获取当前发起人
			String username = "";
			try {
				//查询流程业务关联配置
				LambdaQueryWrapper<ExtActProcessForm> queryWrapper = new LambdaQueryWrapper<ExtActProcessForm>();
				queryWrapper.eq(ExtActProcessForm::getRelationCode, flowCode);
				extActProcessForm = extActProcessFormService.getOne(queryWrapper);
				//获取业务数据，并且加载到流程变量中
				String tableName = extActProcessForm.getFormTableName();
				dataForm = extActProcessService.getDataById(tableName, id);
				dataForm.put(WorkFlowGlobals.BPM_DATA_ID, id);
				dataForm.put(WorkFlowGlobals.BPM_FORM_CONTENT_URL, formUrl);
				if(oConvertUtils.isNotEmpty(formUrlMobile)){
					dataForm.put(WorkFlowGlobals.BPM_FORM_CONTENT_URL_MOBILE, formUrlMobile);
				}else{
					//没有传移动端表单，默认用PC端
					dataForm.put(WorkFlowGlobals.BPM_FORM_CONTENT_URL_MOBILE, formUrl);
				}
				dataForm.put(WorkFlowGlobals.BPM_FORM_KEY, tableName);
				username = JwtUtil.getUserNameByToken(request);
			} catch (Exception e) {
				e.printStackTrace();
				throw new BpmException("获取流程信息异常");
			}
			ProcessInstance processInstance = extActProcessService.startMutilProcess(username, id, dataForm, extActProcessForm);
			log.info("启动成功流程实例 ProcessInstance: ",processInstance);
			result.setResult(processInstance.getProcessInstanceId());
		} catch (ActivitiException e) {
			String message = "启动流程失败";
			if (e.getMessage().indexOf("no processes deployed with key") != -1) {
				message = "没有部署流程!,请在流程配置中部署流程!";
			} else if (e.getMessage().indexOf("Error while evaluating expression") != -1) {
				message = "启动流程失败,流程表达式异常!";
				try {
					message += e.getCause().getCause().getMessage();
				} catch (Exception e1) {
				}
			} else {
				message = "启动流程失败!请确认流程和表单是否关联!";
			}
			result.error500(message);
			Object actObj = e.getCause();
			if(actObj!=null){
				Throwable throwable = (Throwable)actObj;
				if(throwable.getCause()!=null&&throwable.getCause() instanceof BpmException){
					result.error500("启动流程失败:"+throwable.getCause().getMessage());
				}
			}
			e.printStackTrace();
		} catch (BpmException e) {
			result.error500("启动流程失败:"+e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			result.error500("启动流程失败!,请确认流程和表单是否关联!");
			e.printStackTrace();
			Object actObj = e.getCause();
			if(actObj!=null){
				Throwable throwable = (Throwable)actObj;
				if(throwable.getCause()!=null&&throwable.getCause() instanceof BpmException){
					result.error500("启动流程失败:"+throwable.getCause().getMessage());
				}
			}
		}
		return result;
	}

	//update-begin--- author:scott---date:20200313------for:移动OA统一草稿箱功能（online表单+设计器表单）,在保存表单时，判断关联流程的话则往流程中间表插入表单数据------------
	/**
	 * 流程单据保存草稿（online，自定义开发）
	 * @param map
	 * @param request
	 * @return
	 */
	@PostMapping(value = "saveMutilProcessDraft")
	public Result<Object> saveMutilProcessDraft(@RequestBody HashMap<String, String> map,HttpServletRequest request) {
		String flowCode = map.get("flowCode");
		String id = map.get("id");
		String formUrl = map.get("formUrl");
		String formUrlMobile = map.get("formUrlMobile");
		Result<Object> result = new Result<Object>();
		try {
			if(oConvertUtils.isEmpty(flowCode)) {
				throw new BpmException("flowCode参数不能为空");
			}
			if(oConvertUtils.isEmpty(id)) {
				throw new BpmException("id参数不能为空");
			}
			ExtActProcessForm extActProcessForm = null;
			//获取当前发起人
			String username = JwtUtil.getUserNameByToken(request);
			try {
				//查询流程业务关联配置
				LambdaQueryWrapper<ExtActProcessForm> queryWrapper = new LambdaQueryWrapper<ExtActProcessForm>();
				queryWrapper.eq(ExtActProcessForm::getRelationCode, flowCode);
				extActProcessForm = extActProcessFormService.getOne(queryWrapper);
				//获取业务数据，并且加载到流程变量中
				String tableName = extActProcessForm.getFormTableName();
			} catch (Exception e) {
				e.printStackTrace();
				throw new BpmException("获取流程信息异常");
			}
			ExtActFlowData extActFlowData = extActProcessService.saveMutilProcessDraft(username, id, extActProcessForm);
			log.info("保存流程草稿 ExtActFlowData: ",extActFlowData);
			result.setResult(extActFlowData.getId());
		} catch (Exception e) {
			result.error500("保存流程草稿！");
			e.printStackTrace();
		}
		return result;
	}
	//update-end--- author:scott---date:20200313------for:移动OA统一草稿箱功能（online表单+设计器表单）,在保存表单时，判断关联流程的话则往流程中间表插入表单数据------------

	/**
	 * 流程提交接口（表单设计器单据）
	 * @param map
	 * @param request
	 * @return
	 */
	@PostMapping(value = "startDesFormMutilProcess")
	public Result<Object> startDesFormMutilProcess(@RequestBody HashMap<String, String> map,
											HttpServletRequest request) {
		String flowCode = map.get("flowCode");
		String id = map.get("id");
		String formUrl = map.get("formUrl");
		String formUrlMobile = map.get("formUrlMobile");
		String jsonData = map.get("jsonData");
		Result<Object> result = new Result<Object>();
		try {
			if(oConvertUtils.isEmpty(flowCode)) {
				throw new BpmException("flowCode参数不能为空");
			}
			if(oConvertUtils.isEmpty(id)) {
				throw new BpmException("id参数不能为空");
			}
			if(oConvertUtils.isEmpty(formUrl)) {
				throw new BpmException("formUrl参数不能为空");
			}
			ExtActProcessForm extActProcessForm = null;
			Map<String, Object> dataForm = new HashMap<String, Object>();
			//获取当前发起人
			String username = "";
			try {
				//查询流程业务关联配置
				LambdaQueryWrapper<ExtActProcessForm> queryWrapper = new LambdaQueryWrapper<ExtActProcessForm>();
				queryWrapper.eq(ExtActProcessForm::getRelationCode, flowCode);
				extActProcessForm = extActProcessFormService.getOne(queryWrapper);
				//获取业务数据，并且加载到流程变量中
				if(WorkFlowGlobals.BPM_FORM_TYPE_2.equals(extActProcessForm.getFormType())) {
					dataForm = JSONHelper.json2MapNoObj(jsonData);
					dataForm.put(WorkFlowGlobals.BPM_FORM_KEY, WorkFlowGlobals.DESIGN_FORM_DRAFT_TABLE);
				}else {
					throw new BpmException("该请求不支持该业务");
				}
				dataForm.put(WorkFlowGlobals.BPM_DATA_ID, id);
				dataForm.put(WorkFlowGlobals.BPM_FORM_CONTENT_URL, formUrl);
				if(oConvertUtils.isNotEmpty(formUrlMobile)){
					dataForm.put(WorkFlowGlobals.BPM_FORM_CONTENT_URL_MOBILE, formUrlMobile);
				}else{
					//没有传移动端表单，默认用PC端
					dataForm.put(WorkFlowGlobals.BPM_FORM_CONTENT_URL_MOBILE, formUrl);
				}
				username = JwtUtil.getUserNameByToken(request);
			} catch (Exception e) {
				e.printStackTrace();
				throw new BpmException("获取流程信息异常");
			}
			log.debug("---- 发起流程方法 -- startDesFormMutilProcess----id------"+id);
			log.debug("---- 发起流程方法 -- startDesFormMutilProcess----dataForm------"+dataForm);
			log.debug("---- 发起流程方法 -- startDesFormMutilProcess----extActProcessForm------"+extActProcessForm);
			log.debug("---- 发起流程方法 -- startDesFormMutilProcess----username------"+username);
			extActProcessService.startDesFormMutilProcess(username, id, dataForm, extActProcessForm);
		} catch (ActivitiException e) {
			String message = "启动流程失败";
			if (e.getMessage().indexOf("no processes deployed with key") != -1) {
				message = "没有部署流程!,请在流程配置中部署流程!";
			} else if (e.getMessage().indexOf("Error while evaluating expression") != -1) {
				message = "启动流程失败,流程表达式异常!";
				try {
					message += e.getCause().getCause().getMessage();
				} catch (Exception e1) {
				}
			} else {
				message = "启动流程失败!请确认流程和表单是否关联!";
			}
			result.error500(message);
			Object actObj = e.getCause();
			if(actObj!=null){
				Throwable throwable = (Throwable)actObj;
				if(throwable.getCause()!=null&&throwable.getCause() instanceof BpmException){
					result.error500("启动流程失败:"+throwable.getCause().getMessage());
				}
			}
			e.printStackTrace();
		} catch (BpmException e) {
			result.error500("启动流程失败:"+e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			result.error500("启动流程失败!,请确认流程和表单是否关联!");
			e.printStackTrace();
			Object actObj = e.getCause();
			if(actObj!=null){
				Throwable throwable = (Throwable)actObj;
				if(throwable.getCause()!=null&&throwable.getCause() instanceof BpmException){
					result.error500("启动流程失败:"+throwable.getCause().getMessage());
				}
			}
		}
		return result;
	}

	/**
	 * 流程复制功能
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "copyProcess")
	public Result<Object> copyProcess(@RequestParam(name = "id", required = true) String id,HttpServletRequest request, HttpServletResponse response) {
		ExtActProcess extActProcessEntity = extActProcessService.getById(id);

		String newProcessKey = extActProcessEntity.getProcessKey()+"_Copy"+ System.currentTimeMillis();
		String newProcessName = extActProcessEntity.getProcessName()+"_Copy"+ System.currentTimeMillis();
		String bpmxml = new String(extActProcessEntity.getProcessXml());
		bpmxml = bpmxml.replace(extActProcessEntity.getProcessKey(),newProcessKey);
		bpmxml = bpmxml.replace(extActProcessEntity.getProcessName(),newProcessName);

		extActProcessEntity.setId(null);
		extActProcessEntity.setProcessKey(newProcessKey);
		extActProcessEntity.setProcessName(newProcessName);
		extActProcessEntity.setProcessXml(bpmxml.getBytes());
		extActProcessEntity.setProcessStatus(WorkFlowGlobals.Process_Deploy_NO);
		extActProcessEntity.setCreateBy(null);
		extActProcessEntity.setCreateTime(new Date());
		extActProcessService.save(extActProcessEntity);
		//查询流程设计信息（流程主表、节点表、流程权限配置）
		LambdaQueryWrapper<ExtActProcessNode> queryWrapper = new LambdaQueryWrapper<ExtActProcessNode>();
		queryWrapper.eq(ExtActProcessNode::getProcessId, id);
		List<ExtActProcessNode> listNodes = extActProcessNodeService.list(queryWrapper);
		for(ExtActProcessNode node:listNodes){
			node.setId(null);
			node.setProcessId(extActProcessEntity.getId());
			extActProcessNodeService.save(node);
		}
		//ext_act_process、ext_act_process_form、ext_act_process_node、ext_act_process_node_auth
		//流程设计的状态改为未发布
		return Result.ok("流程复制成功！");
	}

     /**
      * 导入流程文件
      *
      * @return
      */
     @ResponseBody
     @RequestMapping(value = "uploadProcess")
     public Result<?> uploadProcess(HttpServletRequest request, HttpServletResponse response) {
         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
         Map<String, MultipartFile> files = multipartRequest.getFileMap();
         List<String> urls = new ArrayList<>();
         for (Map.Entry<String, MultipartFile> entry : files.entrySet()) {
             MultipartFile file = entry.getValue();// 获取上传文件对象
             String fileName = file.getOriginalFilename();
             try {
                 InputStream fileInputStream = file.getInputStream();
                 //通过流程ID，获取流程
                 String id = request.getParameter("id");
                 ExtActProcess extActProcess = extActProcessService.getById(id);
                 String bpmxml = inputStream2String(fileInputStream);
                 if(bpmxml.indexOf("<?xml")==-1){
					 return Result.error("流程导入失败："+ "文件格式错误！");
				 }
                 extActProcess.setProcessXml(bpmxml.getBytes());
                 extActProcessService.updateById(extActProcess);//保存流程

				 //删除原流程节点配置
				 LambdaQueryWrapper<ExtActProcessNode> queryWrapper = new LambdaQueryWrapper<ExtActProcessNode>();
				 queryWrapper.eq(ExtActProcessNode::getProcessId, id);
				 extActProcessNodeService.remove(queryWrapper);
             } catch (Exception e) {
                 log.error("错误信息:在部署过程中,文件输入流异常" + e.toString());
				 return Result.error("流程导入失败："+ e.toString());
             }
         }
		 return Result.ok("流程导入成功!");
     }

    String inputStream2String(InputStream is) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = in.readLine()) != null){
            buffer.append(line);
        }
        return buffer.toString();
    }

}
